import { getCampuses, createCampus, updateCampus, deleteCampus } from '@/lib/campusService'
import CampusManagement from './CampusManagement'
export default async function CampusesPage() {
  const campuses = await getCampuses({  })

  const handleCreateCampus = async (campus) => {
    'use server'
    try {
      //remove id from campusData
      delete campus.id
      const newCampus = await createCampus(campus)
      return { success: true, newCampus }
    } catch (error) {
      console.error('Failed to create campus:', error)
      return { message: '创建校区失败,请稍后再试' }
    }
  }

  const handleUpdateCampus = async ( campus) => {
    'use server'
    try {
      const campusId = campus.id
      await updateCampus(campusId, campus)
      return { success: true }
    } catch (error) {
      console.error('Failed to update campus:', error)
      return { message: '更新校区失败,请稍后再试' }
    }
  }

  const handleDeleteCampus = async (campus) => {
    'use server'
    try {
      const campusId = campus.id
      await deleteCampus(campusId)
      return { success: true }
    } catch (error) {
      console.error('Failed to delete campus:', error)
      return { message: '删除校区失败,请稍后再试' }
    }
  }

  return (
    <CampusManagement
      initialCampuses={campuses}
      getAllCampuses={getCampuses}
      createCampus={handleCreateCampus}
      updateCampus={handleUpdateCampus}
      deleteCampus={handleDeleteCampus}
    />
  )
}